<script setup>
import { Toast } from 'vant';
import { ref, provide, toRaw } from 'vue'
import types from "./controls/controls";

let props = defineProps({
    formData: {
        type: Object,
        default: {
            controls: [],
            props: {
                labelPosition: "right",
                labelWidth: 100,
                size: "default",
                customClass: "",
                cols: 12,
            }
        },
        required: true,
    },
    uploadOptions: {
        type: Object,
        default: {
            action: '',
            getHeaders: () => ({}),
            getFileHook: (response, file) => ({ name: file, url: response.url })
        }
    },
    formModel: {
        type: Object,
        default: {},
        required: true,
    },

})

provide('uploadOptions', props.uploadOptions);

let form = ref(null);
//验证，回调传入是否验证成功
function validate(callback) {
    form.value.validate(callback);
}
// function resetFields() {
//     form.value.resetFields();
// }
// function clearValidate(ps) {
//     form.value.clearValidate(ps);
// }
function scrollToField(prop) {
    form.value.scrollToField(prop)
}
function submit() {
    form.value.submit();
}

defineExpose({
    validate,
    scrollToField,
    submit
});
let emit = defineEmits(['submit']);
function onSubmit() {
    emit('submit', toRaw(props.formModel));
}
function onFailed(errorInfo) {
    Toast.fail('请填写完整再提交');
}
</script>

<template>
    <van-form ref="form" @failed="onFailed" @submit="onSubmit">
        <van-cell-group>
            <component
                v-for="(element, index) in formData.controls"
                :key="index"
                :is="types[element.type].Renderer"
                :control="element"
                :model="formModel"
            />
        </van-cell-group>
    </van-form>
</template>


